<?php
/**
 * Created by PhpStorm.
 * User: dolia
 * Date: 2016/5/12
 * Time: 10:05
 */

namespace App\Http\Controllers\Api\V1;

use App\Exceptions\Api\ApiDoneErrorException;
use App\Exceptions\Api\ApiInputErrorException;
use App\Exceptions\Api\ApiRsaEecryptErrorException;
use App\Exceptions\Api\ApiUserNotLoginErrorException;
use App\Exceptions\Api\ApiValidateErrorException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\ApiRequest as Request;
use App\Interfaces\CategoryService;
use App\Interfaces\SolrService;
use App\Interfaces\GoodsService;
use App\Models\Brand;
use App\Models\Category;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class SearchController extends Controller{

    /**
     * @api {post} /search/search_keyword_goods 根据关键词搜索商品
     * @apiName Search/searchKeywordGoods
     * @apiGroup search
     * @apiDescription 根据关键词搜索商品
     *
     * @apiParam {String[]} [keyword]  搜索关键词
     * @apiParam {int} [stock]  显示有货
     * @apiParam {String} [sort]  排序（销量排序 : sale_desc|sale_asc，价格排序 :price_desc|price_asc）
     * @apiParam {int} [shop_id]  店铺ID
     * @apiParam {int} [page]  当前页
     *
     * @apiSuccess {Object} Object 搜索信息
     * @apiSuccess {Object[]} Object.facetSet 可选信息
     * @apiSuccess {string} Object.facetSet.type 可选信息类型
     * @apiSuccess {Object[]} Object.facetSet.value 可选信息值
     * @apiSuccess {int} Object.facetSet.brand_id.brand_id 品牌ID
     * @apiSuccess {string} Object.facetSet.brand_id.brand_name 品牌名称
     * @apiSuccess {int} Object.filter.brand_id.count 统计该品牌下商品数量
     * @apiSuccess {Object} Object.filter 搜索条件
     * @apiSuccess {string} Object.filter.keyword 关键词
     * @apiSuccess {string} Object.filter.stock 显示有货
     * @apiSuccess {string} Object.filter.sort 排序
     * @apiSuccess {Object} Object.goods 搜索信息
     * @apiSuccess {Object[]} Object.goods.data 商品信息
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
{
    "facetSet": [
        {
            "type": "brand_id",
            "value": [
                {
                "brand_id": 186,
                "brand_name": "Roger &Gallet",
                "count": 1
                },
                {
                "brand_id": 48,
                "brand_name": "雪花秀 Sulwhasoo",
                "count": 1
                },
                {
                "brand_id": 58,
                "brand_name": "雅诗兰黛 Estee Lauder",
                "count": 1
                }
            ]
        }
    ],
    "filter": {
        "keyword": "Organika",
        "stock": 0,
        "sort": ""
    },
    "goods": {
        "total": 2,
        "per_page": 40,
        "current_page": 1,
        "last_page": 1,
        "next_page_url": null,
        "prev_page_url": null,
        "from": 1,
        "to": 2,
        "data": [
        {
            "goods_id": 1330,
            "cat_id": 455,
            "goods_sn": "BL000082",
            "goods_bar_code": null,
            "goods_name": "Organika Estro-G  女性更年乐胶囊  60粒",
            "goods_pet_name": "女士福利 有效缓解更年期症状",
            "goods_desc": "胶囊包含三种草药提取物:朝鲜当归、隔山消和米造苏，共同作用缓解与绝经相关的各种不舒适症状。",
            "brand_id": 163,
            "goods_number": 0,
            "goods_weight": "0.000",
            "market_price": "240.00",
            "shop_price": "160.00",
            "keywords": "Organika, 女性,更年,乐,胶囊",
            "goods_content": "<p><img alt=\"BL000082 副本2.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/67b6c1bf9b881b6ac17df029b541e227.jpg\" width=\"850\" height=\"850\"><br></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【产品介绍】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">EstroG-100缓解更年期症状胶囊包含三种草药提取物:朝鲜当归、隔山消和米造苏，共同作用缓解与绝经相关的各种不舒适症状，如潮热、盗汗、紧张易怒、头晕、阴道干涩、麻木刺痛、情绪不佳、疲劳、失眠等。其作用稳定，安全可靠，&nbsp;纯天然草药提取物，平衡雌性激素活性，缓解更年轻症状。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">适合更年期女性使用，维持体重，平衡雌性激素活性，缓解更年轻症状，缓解潮热盗汗等多种更年轻症状，舒缓压力，保持精神愉悦健康。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【产品成分】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">每粒胶囊含有&nbsp;EEstro-G&nbsp;100.................257毫克</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">朝鲜当归&nbsp;5:1浓缩比例，浓缩精华90毫克，相当于450毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">隔山消&nbsp;5:1浓缩比例，浓缩精华83.5毫克，相当于417.5毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">米造苏&nbsp;5:1浓缩比例，浓缩精华83.5毫克，相当于417.5毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【建议服用】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">每天2次，每次1粒，一杯水吞服</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">&nbsp;</span><span style=\"color: rgb(0, 0, 0); font-size: 10pt;\">&nbsp;</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【什么是Estro-G&nbsp;100？】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">草本植物根提取精华的配方是具有很好功效的，在中国和韩国已经延用了几百年，Estro-G&nbsp;100®最新在北美上市,它不仅能很好改善一些加重的更年期症状,而且比其他女性选择的同类产品效果要快数倍。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">EstroG-100对女性潮热和盗汗,阴道干燥、失眠、紧张、无精打采，头晕，疲劳有很好的改善，一些女性在7&nbsp;-&nbsp;10天内可以看到明显的改善。而其他同类的植物产品则要长达六周才能有明显效果。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">Estro-G&nbsp;100&nbsp;100现在在美国可以作为一个有效的针对更年期症状缓解的产品无需医生处方即可买到的。Estro-G&nbsp;100对更年期症状除了具有很好的效果，它也是市场上最安全的天然选择。研究表明,Estro-G&nbsp;100没有任何对雌激素效应也不影响体重、身体质量指数,或肝脏酶,都是受到其他植物的选择的影响。</span></p>",
            "goods_thumb": "db5a29ea25c698e1360ac7521d07c7dc",
            "resource": "加拿大",
            "type": 0,
            "goods_gallery_id": 0,
            "is_on_sale": 1,
            "add_time": 0,
            "sort_order": 100,
            "is_delete": 0,
            "is_home_recommend": 0,
            "is_cat_recommend": 0,
            "shop_id": 2,
            "sales_num": 0,
            "deleted_at": null,
            "search_keywords": "Organika,,女性,更年,乐,胶囊,Organika,营养保健,营养保健,功能保健品,保健,保养,美容养颜,美容,养颜",
            "created_at": "2016-02-04 16:28:41",
            "updated_at": "2016-02-19 20:30:54",
            "audit_status": 1,
            "mobile_goods_thumb": "http://dolia.img-cn-hangzhou.aliyuncs.com/db5a29ea25c698e1360ac7521d07c7dc.jpg"
        }
     }
}
     */

    public function searchKeywordGoods(Request $request,SolrService $solrService,CategoryService $categoryService,GoodsService $goodsService){

        $filter['keyword'] = addslashes($request->get('keyword'));
        $filter['stock'] = $request->get('stock')?$request->get('stock'):0;
        $filter['sort'] = $request->get('sort')?$request->get('sort'):"";
        $filter['shop_id'] = $request->get('shop_id')?$request->get('shop_id'):"*";
        $result = $solrService->search($filter['keyword'],'*','*',$filter['stock'],$request->get('page'),40,$filter['sort'],$filter['shop_id']);

        //拼装筛选条件
        $facetArr = array();
        foreach($result['facetSet']->getFacets() as $type=>$facet){
            $facetSetItem = ['type'=>'','value'=>[]];

            $typeValues = $facet->getValues();
            if($type=='brand_id'){
                $facetSetItem['type'] = $type;
                foreach ($typeValues as $brand_id=>$count) {
                    $facetSetItem['value'][]= [
                        'brand_id'=>$brand_id,
                        'brand_name'=>Brand::find($brand_id)->brand_name,
                        'count'=>$count
                    ];
                }
            }

        }
        $facetArr[] = $facetSetItem;

        //拼装商品及分页
        $goodsArr = [];
        foreach($result['paginate']->items() as $document ){
            $goodsArr[] = $goodsService->get($document->getFields()['goods_id']);
        }
        $page = $request->get('page') ?: Paginator::resolveCurrentPage('page');

        $paginate =  new LengthAwarePaginator($goodsArr, $result['paginate']->total(), 40, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        //检索品牌
        //$filterCat = $categoryService->getCatByIds(array_keys($catFacet));

        $data = [
            'facetSet'=>$facetArr,
            'filter'=>$filter,
            'goods'=>$paginate->toArray()
        ];
        return response()->json($data);

    }


    /**
     * @api {post} /search/search_cat_goods/{cat_id} 根据条件筛选分类商品
     * @apiName Search/searchCatGoods
     * @apiGroup search
     * @apiDescription 根据条件筛选分类商品
     *
     * @apiParam {int} [cat_id]  选中的分类ID
     * @apiParam {int} [stock]  显示有货
     * @apiParam {string} [sort]  排序（销量排序 : sale_desc|sale_asc，价格排序 :price_desc|price_asc）
     * @apiParam {int} [page]  当前页
     *
     * @apiSuccess {Object} Object 搜索信息
     * @apiSuccess {Object[]} Object.facetSet 可选信息
     * @apiSuccess {string} Object.facetSet.type 可选分类的类型
     * @apiSuccess {Object[]} Object.facetSet.value 可选分类的类型值
     * @apiSuccess {int} Object.facetSet.cat_id.cat_id 分类ID
     * @apiSuccess {string} Object.facetSet.cat_id.cat_id_name 分类名称
     * @apiSuccess {int} Object.filter.cat_id.count 统计该分类下商品数量
     * @apiSuccess {Object} Object.filter 筛选条件
     * @apiSuccess {string} Object.filter.cat_id 分类ID
     * @apiSuccess {string} Object.filter.stock 显示有货
     * @apiSuccess {string} Object.filter.sort 排序
     * @apiSuccess {Object} Object.goods 分页搜索信息
     * @apiSuccess {Object[]} Object.goods.data 商品信息
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "facetSet": [
        {
            "type": "cat_id",
            "value": [
                {
                "cat_id": 23,
                "cat_name": "眼部护理",
                "count": 1
                },
                {
                "cat_id": 389,
                "cat_name": "面部护理",
                "count": 1
                }
            ]
        }
    ],
    "filter": {
    "cat_id": "393",
    "stock": 0,
    "sort": ""
    },
    "goods": {
    "total": 2,
    "per_page": 40,
    "current_page": 1,
    "last_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 2,
    "data": [
    {
    "goods_id": 1330,
    "cat_id": 455,
    "goods_sn": "BL000082",
    "goods_bar_code": null,
    "goods_name": "Organika Estro-G  女性更年乐胶囊  60粒",
    "goods_pet_name": "女士福利 有效缓解更年期症状",
    "goods_desc": "胶囊包含三种草药提取物:朝鲜当归、隔山消和米造苏，共同作用缓解与绝经相关的各种不舒适症状。",
    "brand_id": 163,
    "goods_number": 0,
    "goods_weight": "0.000",
    "market_price": "240.00",
    "shop_price": "160.00",
    "keywords": "Organika, 女性,更年,乐,胶囊",
    "goods_content": "<p><img alt=\"BL000082 副本2.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/67b6c1bf9b881b6ac17df029b541e227.jpg\" width=\"850\" height=\"850\"><br></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【产品介绍】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">EstroG-100缓解更年期症状胶囊包含三种草药提取物:朝鲜当归、隔山消和米造苏，共同作用缓解与绝经相关的各种不舒适症状，如潮热、盗汗、紧张易怒、头晕、阴道干涩、麻木刺痛、情绪不佳、疲劳、失眠等。其作用稳定，安全可靠，&nbsp;纯天然草药提取物，平衡雌性激素活性，缓解更年轻症状。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">适合更年期女性使用，维持体重，平衡雌性激素活性，缓解更年轻症状，缓解潮热盗汗等多种更年轻症状，舒缓压力，保持精神愉悦健康。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【产品成分】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">每粒胶囊含有&nbsp;EEstro-G&nbsp;100.................257毫克</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">朝鲜当归&nbsp;5:1浓缩比例，浓缩精华90毫克，相当于450毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">隔山消&nbsp;5:1浓缩比例，浓缩精华83.5毫克，相当于417.5毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">米造苏&nbsp;5:1浓缩比例，浓缩精华83.5毫克，相当于417.5毫克植物</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【建议服用】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">每天2次，每次1粒，一杯水吞服</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">&nbsp;</span><span style=\"color: rgb(0, 0, 0); font-size: 10pt;\">&nbsp;</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">【什么是Estro-G&nbsp;100？】</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">草本植物根提取精华的配方是具有很好功效的，在中国和韩国已经延用了几百年，Estro-G&nbsp;100®最新在北美上市,它不仅能很好改善一些加重的更年期症状,而且比其他女性选择的同类产品效果要快数倍。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">EstroG-100对女性潮热和盗汗,阴道干燥、失眠、紧张、无精打采，头晕，疲劳有很好的改善，一些女性在7&nbsp;-&nbsp;10天内可以看到明显的改善。而其他同类的植物产品则要长达六周才能有明显效果。</span></p><p><span style=\"font-size: 10pt; color: rgb(0, 0, 0);\">Estro-G&nbsp;100&nbsp;100现在在美国可以作为一个有效的针对更年期症状缓解的产品无需医生处方即可买到的。Estro-G&nbsp;100对更年期症状除了具有很好的效果，它也是市场上最安全的天然选择。研究表明,Estro-G&nbsp;100没有任何对雌激素效应也不影响体重、身体质量指数,或肝脏酶,都是受到其他植物的选择的影响。</span></p>",
    "goods_thumb": "db5a29ea25c698e1360ac7521d07c7dc",
    "resource": "加拿大",
    "type": 0,
    "goods_gallery_id": 0,
    "is_on_sale": 1,
    "add_time": 0,
    "sort_order": 100,
    "is_delete": 0,
    "is_home_recommend": 0,
    "is_cat_recommend": 0,
    "shop_id": 2,
    "sales_num": 0,
    "deleted_at": null,
    "search_keywords": "Organika,,女性,更年,乐,胶囊,Organika,营养保健,营养保健,功能保健品,保健,保养,美容养颜,美容,养颜",
    "created_at": "2016-02-04 16:28:41",
    "updated_at": "2016-02-19 20:30:54",
    "audit_status": 1,
    "mobile_goods_thumb": "http://dolia.img-cn-hangzhou.aliyuncs.com/db5a29ea25c698e1360ac7521d07c7dc.jpg"
    }
    }
    }
     */
    public function searchCatGoods($cat_id,Request $request, GoodsService $goodsService,CategoryService $categoryService,SolrService $solrService){

        $cat = Category::find($cat_id);

        $depth = $cat->getDepth();

        if($depth==1){

            throw new ApiDoneErrorException("不支持顶级分类调用");

        }elseif($depth==2||$depth==3){
            if ($depth==2){
                $cat_ids = $categoryService->getChildIds($cat_id)->toArray();
            }else{
                $cat_ids = $categoryService->getBrotherIds($cat_id)->toArray();
            }

            if ($depth==3 && !$request->get('cat_id')){
                $filter['cat_id'] = $cat_id;
                //检索分类
                //$filterCategory = $categoryService->getPath($cat_id);
            }elseif ($depth==3 && $request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                //$filterCategory = $categoryService->getPath($request->get('cat_id'));
            }elseif ($depth!=3 && $request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                //$filterCategory = $categoryService->getPath($request->get('cat_id'));
            }elseif ($depth!=3 && !$request->get('cat_id')){
                $filter['cat_id'] = $request->get('cat_id');
                //检索分类
                //$filterCategory = $categoryService->getPath($cat_id);
            }

            $filter['stock'] = $request->get('stock')?intval($request->get('stock')):0;
            $filter['sort'] = $request->get('sort')?$request->get('sort'):"";

            $result = $solrService->category($cat_ids,$filter['cat_id'],'*',$filter['stock'],$request->get('page'),40,$filter['sort']);

            //拼装筛选条件

            $facetSet = array();
            //dd($result['facetSet']->getFacets());
            foreach($result['facetSet']->getFacets() as $type=>$facet){

                $facetSetItem = ['type'=>'','value'=>[] ];

                $typeValues = $facet->getValues();

                if ($type=='cat_id'){

                    $facetSetItem['type'] = $type;

                    foreach($typeValues as $cat_id=>$count){
                        $facetSetItem['value'][] = [
                            'cat_id'=>$cat_id,
                            'cat_name'=>Category::find($cat_id)->cat_name,
                            'count'=>$count
                        ];
                    }
                    //dd($item);
                }
                $facetSet[] = $facetSetItem;
                //....品牌 其他
            }

            //拼装商品及分页
            $goodsArr = [];
            foreach($result['paginate']->items() as $document ){
                $goodsArr[] = $goodsService->get($document->getFields()['goods_id']);
            }

            $page = $request->get('page') ?: Paginator::resolveCurrentPage('page');
            //dd($goodsArr);
            $paginate =  new LengthAwarePaginator($goodsArr, $result['paginate']->total(), 40, $page, [
                'path' => Paginator::resolveCurrentPath(),
                'pageName' => 'page',
            ]);

            $data = [
                'facetSet'=>$facetSet,
                'filter'=>$filter,
                'goods'=>$paginate->toArray()
            ];

            return response()->json($data);
        }

    }



} 